<?php
/**
 * Created by PhpStorm.
 * User: xiangfeng
 * Date: 2022/4/15
 * Time: 1:54 PM
 */

namespace app\api\http\middleware;

use app\api\extend\tools\JwtAuth;
use app\api\http\exceptions\ApiErr;
use app\api\http\exceptions\ApiExceptions;
use app\api\service\UserService;
use think\Request;

/**
 * 用户中间价
 * Class MemberMiddleware
 * @package app\api\http\middleware
 */
class MemberMiddleware extends BaseMiddleware
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     * @throws ApiExceptions
     */
    public function handle(Request $request, \Closure $next)
    {
        $redis = $this->redis;
        $header = $request->header();
        $token = isset($header['token']) ? $header['token'] : '';
        $jwtAuth = JwtAuth::getInstance();
        if ($token && $token != "null") {
            $jwtAuth->setToken($token);
            if ($jwtAuth->validateToken() && $jwtAuth->verifyToken()) {
                $uid = $jwtAuth->decode_jwt_token()->getClaim('uid');
                $rid = $jwtAuth->decode_jwt_token()->getClaim('rid');
                $redis_token = $redis->hGetAll(USER_TOKEN_PREFIX . md5($token)); //获取缓存用户数据
                $cache_token = isset($redis_token['token']) ? $redis_token['token'] : '';
                $user_id = isset($redis_token['user_id']) ? (int)$redis_token['user_id'] : 0;
                $role_id = isset($redis_token['role_id']) ? (int)$redis_token['role_id'] : 0;
                if ($token != $cache_token) {
                    throw new ApiExceptions(ApiErr::ERROR_TOKEN);
                }
                if ($user_id != $uid || $role_id != $rid) {
                    throw new ApiExceptions(ApiErr::ILLEGAL_USER_WARRING);
                }
                $isCerStatus = UserService::checkUserIsCertification($user_id);
                if (!$isCerStatus) throw new ApiExceptions(ApiErr::USER_ACC_NO_CERT);
                return $next($request);
            } else {
                throw new ApiExceptions(ApiErr::ERROR_TOKEN);
            }
        } else {
            throw new ApiExceptions(ApiErr::ERROR_TOKEN);
        }
    }
}